import 'dart:async';

import 'package:jyofservice/bean/dy_list_entity.dart';
import 'package:jyofservice/bean/glz_list_entity.dart';
import 'package:jyofservice/bean/hrz_list_entity.dart';
import 'package:jyofservice/bean/lh_list_entity.dart';
import 'package:jyofservice/bean/xq_list_entity.dart';
import 'package:jyofservice/fluro/NavigatorUtil.dart';
import 'package:jyofservice/util/CallRecordNotification.dart';
import 'package:jyofservice/util/Constants.dart';
import 'package:jyofservice/util/RefreshBottomSheetEvent.dart';
import 'package:jyofservice/util/webconfig.dart';
import 'package:flutter/material.dart';
import 'package:flutter_spinkit/flutter_spinkit.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:dio/dio.dart';
import 'package:fluttertoast/fluttertoast.dart';

class LevelTree extends StatefulWidget {
  @override
  _LevelTreeState createState() => _LevelTreeState();
}

class _LevelTreeState extends State<LevelTree> {
  List<XqListEntity?> xqlist = [];
  List<LhListEntity?> lhList = [];
  List<DyListEntity?> dyList = [];
  List<HrzListEntity?> hrzList = [];
  List<GlzListEntity?> glzList = [];
  String? showXQ;
  String? showLH;
  String? showDY;
  String? showHrz;
  String? showGls;

  late StreamSubscription subscription;
  TextEditingController searchController = TextEditingController();
  TextEditingController lhController = TextEditingController();
  bool isloading = true;
  StateSetter? _glzState;
  StateSetter? _hrzState;
  StateSetter? _xqState;
  StateSetter? _lhState;
  StateSetter? _dyState;
  StateSetter? _mphState;
  int index = 0;
  String? selectXQ="";
  String? selectLH = "";
  String? selectDY="";

  @override
  void initState() {
    // TODO: implement initState
    super.initState();

    subscription = eventBus.on<RefreshBottomSheetEvent>().listen((event) {
      if (mounted) {
        setState(() {});
      }
      int index = event.index;
      switch (index) {
        case 1:
          if (_xqState != null) {
            if (mounted) {
              _xqState!(() {});
            }
          }
          break;
        case 2:
          if (_lhState != null) {
            if (mounted) {
              _lhState!(() {});
            }
          }
          _xqState = null;
          break;
        case 3:
          if (_dyState != null) {
            if (mounted) {
              _dyState!(() {});
            }
          }
          _lhState = null;
          break;
        case 4:
          if (_mphState != null) {
            if (mounted) {
              _mphState!(() {});
            }
          }
          _dyState = null;
          break;
      }
    });
    subscription.resume();

    // getGlzData();

    //按照小区模糊查询
    getXqVagueData("");

  }

  @override
  Widget build(BuildContext context) {
    return Drawer(
        child: Stack(
      children: <Widget>[
        Column(
          children: <Widget>[
            AppBar(
              centerTitle: true,
              title: Text(
                '编码查询',
                style: TextStyle(
                    color: Colors.white, fontSize: ScreenUtil().setSp(45)),
              ),
              actions: <Widget>[
                SizedBox(
                  width: 30,
                )
              ],
            ),
            Container(
              width: ScreenUtil().scaleWidth,
              height: ScreenUtil().setHeight(2),
              color: Colors.grey,
            ),
            Expanded(
              child: getAddressItem(),
            ),
            Container(
              color: Colors.white,
              margin: EdgeInsets.only(bottom: ScreenUtil().bottomBarHeight),
              alignment: Alignment.bottomCenter,
              child: Row(
                children: <Widget>[
                  Expanded(
                    child: Container(
                        decoration: BoxDecoration(
                          border: Border.all(width: 1.0, color: Colors.blue),
                          color: Colors.blue,
                        ),
                        height: 60.0,
                        child: TextButton(
                          child: Text(
                            "查询",
                            style: TextStyle(
                                color: Colors.white,
                                fontSize: ScreenUtil().setSp(35)),
                          ),
                          onPressed: () {
                            _chaxun();
                          },
                        )),
                  ),
                ],
              ),
            )
          ],
        ),
        Offstage(
          offstage: isloading,
          child: SpinKitFadingCircle(
            color: Colors.blue,
            size: 50.0,
          ),
        )
      ],
    ));
  }

  Widget getAddressItem() {
    return Container(
      color: Colors.white,
      padding: EdgeInsets.all(10),
      child: SingleChildScrollView(
          child: Column(
        children: <Widget>[
          // _glzbuildItem(),
          // _hrzbuildItem(),
          _xqbuildItem(),
          _lhbuildItem(),
          _dybuildItem(),

        ],
      )),
    );
  }

  Widget _dybuildItem() {
    return ListTile(
      title: Text(
        showDY ?? "请选择单元",
        style: TextStyle(fontSize: ScreenUtil().setSp(35)),
      ),
      leading: CircleAvatar(
        backgroundColor: Colors.blue,
        child: Text(
          '单元',
          style: TextStyle(color: Colors.white),
        ),
      ),
      trailing: Icon(Icons.keyboard_arrow_right),
      onTap: () {
        showModalBottomSheet(
            context: context,
            builder: (BuildContext context) {
              return StatefulBuilder(
                builder: (context1, state) {
                  _dyState = state;
                  return Stack(
                    children: <Widget>[
                      Column(
                        children: <Widget>[
                          Expanded(
                              child: ListView.builder(
                            itemBuilder: (context, item) {
                              return _dyitemBuilder(item);
                            },
                            itemCount: dyList.length,
                          ))
                        ],
                      ),
                      Offstage(
                        offstage: dyList.length > 0 ? true : false,
                        child: SpinKitFadingCircle(
                          color: Colors.blue,
                          size: 50.0,
                        ),
                      )
                    ],
                  );
                },
              );
            });
      },
    );
  }

  Widget _dyitemBuilder(int item) {
    return TextButton(
      child: Text(
        dyList[item]?.dy ?? '',
        style: TextStyle(color: Colors.black, fontSize: ScreenUtil().setSp(40)),
      ),
      onPressed: () {
        Navigator.pop(context);
        showDY = dyList[item]!.dy;
        selectDY=dyList[item]!.dy;
        if (mounted) {
          setState(() {});
        }
      },
    );
  }

  Widget _lhbuildItem() {
    return ListTile(
      title: Text(
        showLH ?? "请选择楼号",
        style: TextStyle(fontSize: ScreenUtil().setSp(35)),
      ),
      leading: CircleAvatar(
        backgroundColor: Colors.blue,
        child: Text(
          '楼号',
          style: TextStyle(color: Colors.white),
        ),
      ),
      trailing: Icon(Icons.keyboard_arrow_right),
      onTap: () {
        showModalBottomSheet(
            context: context,
            builder: (BuildContext context) {
              return StatefulBuilder(
                builder: (context1, state) {
                  _lhState = state;
                  return Stack(
                    children: <Widget>[
                      Column(
                        children: <Widget>[
                          Expanded(
                              child: ListView.builder(
                            itemBuilder: (context, item) {
                              return _lhitemBuilder(item);
                            },
                            itemCount: lhList.length,
                          ))
                        ],
                      ),
                      Offstage(
                        offstage: lhList.length > 0 ? true : false,
                        child: SpinKitFadingCircle(
                          color: Colors.blue,
                          size: 50.0,
                        ),
                      )
                    ],
                  );
                },
              );
            });
      },
    );
  }

  Widget _lhitemBuilder(int item) {
    return TextButton(
      child: Text(
        lhList[item]?.lh ?? '',
        style: TextStyle(color: Colors.black, fontSize: ScreenUtil().setSp(40)),
      ),
      onPressed: () {
        Navigator.pop(context);
        showLH = lhList[item]!.lh;
        showDY = "请选择单元";
        selectLH=lhList[item]!.lh;
        selectDY="";
        getDYData(item);
        if (mounted) {
          setState(() {});
        }
      },
    );
  }

  Widget _xqbuildItem() {
    return ListTile(
      title: Text(
        showXQ ?? "请选择小区",
        style: TextStyle(fontSize: ScreenUtil().setSp(35)),
      ),
      leading: CircleAvatar(
        backgroundColor: Colors.blue,
        child: Text(
          '小区',
          style: TextStyle(color: Colors.white),
        ),
      ),
      trailing: Icon(Icons.keyboard_arrow_right),
      onTap: () {
        showModalBottomSheet(
            context: context,
            builder: (BuildContext context) {
              return StatefulBuilder(
                builder: (context1, state) {
                  _xqState = state;
                  return Stack(
                    children: <Widget>[
                      Column(
                        children: <Widget>[
                          Row(
                            children: <Widget>[
                              Container(
                                  margin: EdgeInsets.only(left: 10),
                                  child: Icon(Icons.search)),
                              Expanded(
                                child: TextField(
                                    controller: searchController,
                                    onSubmitted: (str) {
                                      getXqVagueData(str).then((onValue) {
                                        if (onValue != null) {
                                          state(() {});
                                        }
                                      });
                                    },
                                    decoration: InputDecoration(
                                      hintText: '小区搜索',
                                      hintStyle: TextStyle(
                                          fontSize: ScreenUtil().setSp(35.0)),
                                    )),
                              ),
                              TextButton(
                                child: Text(
                                  '确定',
                                  style: TextStyle(
                                      color: Colors.orange,
                                      fontSize: ScreenUtil().setSp(37)),
                                ),
                                onPressed: () {
                                  getXqVagueData(searchController.text.toString())
                                      .then((onValue) {
                                    if (onValue != null) {
                                      state(() {});
                                    }
                                  });
                                },
                              )
                            ],
                          ),
                          Expanded(
                            child: ListView.builder(
                              itemBuilder: (context, item) {
                                return _xqitemBuilder(item);
                              },
                              itemCount: xqlist.length,
                            ),
                          ),
                        ],
                      ),
                      Offstage(
                        offstage: xqlist.length > 0 ? true : false,
                        child: SpinKitFadingCircle(
                          color: Colors.blue,
                          size: 50.0,
                        ),
                      )
                    ],
                  );
                },
              );
            });
      },
    );
  }

  Widget _xqitemBuilder(int item) {
    return TextButton(
      child: Text(
        xqlist[item]?.xqName ?? '',
        style: TextStyle(color: Colors.black, fontSize: ScreenUtil().setSp(40)),
      ),
      onPressed: () {
        Navigator.pop(context);
        showXQ = xqlist[item]!.xqName;
        showLH = "请选择楼号";
        showDY = "请选择单元";
        dyList.clear();
        selectXQ = xqlist[item]!.xqCode;
        selectLH="";
        selectDY="";
        getLHData(item);
        if (mounted) {
          setState(() {});
        }
      },
    );
  }

  Widget _hrzitemBuilder(int item) {
    return TextButton(
      child: Text(
        hrzList[item]?.hrzName ?? '',
        style: TextStyle(color: Colors.black, fontSize: ScreenUtil().setSp(40)),
      ),
      onPressed: () {
        Navigator.pop(context);
        showHrz = hrzList[item]!.hrzName;
        getXqData(item);
        selectXQ="";
        selectLH="";
        selectDY="";
        if (mounted) {
          setState(() {});
        }
      },
    );
  }

  Widget _hrzbuildItem() {
    return ListTile(
      title: Text(
        showHrz ?? "请选择换热站",
        style: TextStyle(fontSize: ScreenUtil().setSp(35)),
      ),
      leading: CircleAvatar(
        backgroundColor: Colors.blue,
        child: Text(
          '热站',
          style: TextStyle(color: Colors.white),
        ),
      ),
      trailing: Icon(Icons.keyboard_arrow_right),
      onTap: () {
        showModalBottomSheet(
            context: context,
            builder: (BuildContext context) {
              return StatefulBuilder(
                builder: (context1, state) {
                  _hrzState = state;
                  return Stack(
                    children: <Widget>[
                      Column(
                        children: <Widget>[
                          Expanded(
                              child: ListView.builder(
                                itemBuilder: (context, item) {
                                  return _hrzitemBuilder(item);
                                },
                                itemCount: hrzList.length,
                              ))
                        ],
                      ),
                      Offstage(
                        offstage: hrzList.length > 0 ? true : false,
                        child: SpinKitFadingCircle(
                          color: Colors.blue,
                          size: 50.0,
                        ),
                      )
                    ],
                  );
                },
              );
            });
      },
    );
  }

  Widget _glzitemBuilder(int item) {
    return TextButton(
      child: Text(
        glzList[item]?.glzName ?? '',
        style: TextStyle(color: Colors.black, fontSize: ScreenUtil().setSp(40)),
      ),
      onPressed: () {
        Navigator.pop(context);
        showGls = glzList[item]!.glzName;
        getHrzData(item);
        selectXQ="";
        selectLH="";
        selectDY="";
        if (mounted) {
          setState(() {});
        }
      },
    );
  }

  Widget _glzbuildItem() {
    return ListTile(
      title: Text(
        showGls ?? "请选择管理站",
        style: TextStyle(fontSize: ScreenUtil().setSp(35)),
      ),
      leading: CircleAvatar(
        backgroundColor: Colors.blue,
        child: Text(
          '管站',
          style: TextStyle(color: Colors.white),
        ),
      ),
      trailing: Icon(Icons.keyboard_arrow_right),
      onTap: () {
        showModalBottomSheet(
            context: context,
            builder: (BuildContext context) {
              return StatefulBuilder(
                builder: (context1, state) {
                  _glzState = state;
                  return Stack(
                    children: <Widget>[
                      Column(
                        children: <Widget>[
                          Expanded(
                              child: ListView.builder(
                                itemBuilder: (context, item) {
                                  return _glzitemBuilder(item);
                                },
                                itemCount: glzList.length,
                              ))
                        ],
                      ),
                      Offstage(
                        offstage: glzList.length > 0 ? true : false,
                        child: SpinKitFadingCircle(
                          color: Colors.blue,
                          size: 50.0,
                        ),
                      )
                    ],
                  );
                },
              );
            });
      },
    );
  }

  Future getGlzData() async {
    glzList.clear();
    try {
      Response response = await Dio().get(
        WebConfig().jichaUrl + "method=get_glz",
      );
      print(response.data.toString());

      for (int i = 0; i < response.data.length; i++) {
        GlzListEntity? glzListEntity =
            GlzListEntity().fromJson(response.data[i]);
        glzList.add(glzListEntity);
      }
      eventBus.fire(RefreshBottomSheetEvent(1));

      return response.data;
    } catch (e) {
      print(e.toString());
    }
  }

  Future getHrzData(int item) async {
    hrzList.clear();
    if (mounted) {
      setState(() {
        isloading = false;
      });
    }
    try {
      Response response = await Dio().get(WebConfig().jichaUrl +
          "method=get_hrz&glz_id=" + glzList[item]!.glzId.toString());
      print(response.data.toString());
      for (int i = 0; i < response.data.length; i++) {
        HrzListEntity? hrzListEntity =
            HrzListEntity().fromJson(response.data[i]);
        hrzList.add(hrzListEntity);
      }

      eventBus.fire(RefreshBottomSheetEvent(2));

      if (mounted) {
        setState(() {
          isloading = true;
        });
      }
      return response.data;
    } catch (e) {
      print(e.toString());
    }
  }

  //按照小区模糊查询
  Future getXqVagueData(String xqName) async {
    if (mounted) {
      setState(() {
        isloading = false;
      });
    }
    xqlist.clear();

    try {
      Response response = await Dio().get(
        WebConfig().jichaUrl +
            "method=get_xq_new&xq_name="+xqName,
      );
      print('${ WebConfig().jichaUrl +
          "method=get_xq_new&xq_name="+xqName}');
      print(response.data.toString());

      for (int i = 0; i < response.data.length; i++) {
        XqListEntity? xqListEntity = XqListEntity().fromJson(response.data[i]);
        xqlist.add(xqListEntity);
      }
      eventBus.fire(RefreshBottomSheetEvent(3));

      if (mounted) {
        setState(() {
          isloading = true;
        });
      }
      return response.data;
    } catch (e) {
      print(e.toString());
    }
  }

  //按照小区查询
  Future getXqData(int item) async {
    if (mounted) {
      setState(() {
        isloading = false;
      });
    }
    xqlist.clear();

    try {
      Response response = await Dio().get(
        WebConfig().jichaUrl +
            "method=get_xq&hrz_id=" +
            hrzList[item]!.hrzId.toString(),
      );
      print(response.data.toString());

      for (int i = 0; i < response.data.length; i++) {
        XqListEntity? xqListEntity = XqListEntity().fromJson(response.data[i]);
        xqlist.add(xqListEntity);
      }
      eventBus.fire(RefreshBottomSheetEvent(3));

      if (mounted) {
        setState(() {
          isloading = true;
        });
      }
      return response.data;
    } catch (e) {
      print(e.toString());
    }
  }

  Future getLHData(int item) async {
    lhList.clear();
    try {
      Response response = await Dio().get(WebConfig().jichaUrl +
          "method=get_lh&xq_code=" +
          xqlist[item]!.xqCode!);
      print(response.data.toString());

      for (int i = 0; i < response.data.length; i++) {
        LhListEntity? lhListEntity = LhListEntity().fromJson(response.data[i]);
        lhList.add(lhListEntity);
      }
      eventBus.fire(RefreshBottomSheetEvent(4));

      return response.data;
    } catch (e) {
      print(e.toString());
    }
  }

  Future getDYData(int item) async {
    dyList.clear();
    try {

      Response response = await Dio().get(
          WebConfig().jichaUrl + "method=get_dy&xq_code="+selectXQ!+"&lh="+lhList[item]!.lh!,);
      print(response.data.toString());


      for (int i = 0; i < response.data.length; i++) {
        DyListEntity? dyListEntity = DyListEntity().fromJson(response.data[i]);
        dyList.add(dyListEntity);
      }
        eventBus.fire(RefreshBottomSheetEvent(5));

      return response.data;
    } catch (e) {
      print(e.toString());
    }
  }

  void _chaxun() {
    if(selectXQ!.length>0){
      NavigatorUtil.goBack(context);
      Constants.eventBus.fire(
          CallRecordNotification(wherestr:"xq_code="+selectXQ!+"&lh="+selectLH!+"&dy="+selectDY!));
    }else{
      Fluttertoast.showToast(msg: '请至少选择至小区');
    }

  }


  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    subscription.cancel();
  }
}
